using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.Forms.CoreLab;
using Microsoft.Practices.EnterpriseLibrary.Data;

using Syncfusion.Windows.Forms.Grid;
using Syncfusion.Windows.Forms.Tools;
using ctsu.Admin.Forms;
using ctsu.BaseForms;
using ctsu.Security;
using ctsu.Shared;

namespace ctsu.Admin.BusLogic.CoreLab
{
	public class BLFormSamplesCheckIn : BLCoreLabFormBaseImpl
	{
		private bool ignoreEvent = false;
		#region control references
		private TextBox _id;
		private DateTimePickerAdv _batchInDate;

		private TextBox _note;
		private CheckBox _notUsed;
		private CheckBox _noShow;

		private ComboBox _freezer;
		private ComboBox _reasonNotUsed;
		private NumericUpDown _shelf;
		private NumericUpDown _rack;
		private NumericUpDown _box;

		private Button _btnUpdateSelected;
		private Button _btnUpdateAll;
		private Button _btnClear;
		private Button _btnRemoveBatch;
		private Button _btnPrint;
		private Button _selectLocation;

		private CheckBox _chkIncludeComment;
		#endregion control references

		public BLFormSamplesCheckIn(FormMain formMain, FormBase form, FormInfoBase formInfo, DataTable tableSchema, Permission formSecurity, Hashtable configData)
			: base(formMain, form, formInfo, tableSchema, formSecurity, configData)
		{
		}

		#region initialize
		protected override void _vcManager_OnAfterHookEvents()
		{
			_id = (TextBox)Forms.Utils.GetControlByName("ID", this._form.Controls);
			_batchInDate = (DateTimePickerAdv)Forms.Utils.GetControlByName("BatchInDate", this._form.Controls);
			_note = (TextBox)Forms.Utils.GetControlByName("Note", this._form.Controls);

			_notUsed = (CheckBox)Forms.Utils.GetControlByName("NotUsed", this._form.Controls);
			_notUsed.CheckedChanged += new EventHandler(_notUsed_CheckedChanged);
			_noShow = (CheckBox)Forms.Utils.GetControlByName("NoShow", this._form.Controls);
			_noShow.CheckedChanged += new EventHandler(_noShow_CheckedChanged);

			_btnUpdateSelected = (Button)Forms.Utils.GetControlByName("btnUpdateSelected", this._form.Controls);
			_btnUpdateAll = (Button)Forms.Utils.GetControlByName("btnUpdateAll", this._form.Controls);
			_btnClear = (Button)Forms.Utils.GetControlByName("btnClear", this._form.Controls);
			_btnRemoveBatch = (Button)Forms.Utils.GetControlByName("btnRemoveBatch", this._form.Controls);
			_selectLocation = (Button)Forms.Utils.GetControlByName("SelectLocation", this._form.Controls);
			_chkIncludeComment = (CheckBox)Forms.Utils.GetControlByName("chkIncludeComment", this._form.Controls);

			_btnPrint = (Button)Forms.Utils.GetControlByName("btnPrint", this._form.Controls);
			_chkPrintSelected = (CheckBox)Forms.Utils.GetControlByName("chkPrintSelected", this._form.Controls);
			_chkPrintReport = (CheckBox)Forms.Utils.GetControlByName("chkPrintReport", this._form.Controls);
			_chkPerPatient = (CheckBox)Forms.Utils.GetControlByName("chkPerPatient", this._form.Controls);

			_reasonNotUsed = (ComboBox)Forms.Utils.GetControlByName("ReasonNotUsed", this._form.Controls);
			_freezer = (ComboBox)Forms.Utils.GetControlByName("Freezer", this._form.Controls);
			_freezer.SelectedIndexChanged += new EventHandler(_location_ValueChanged);
			_shelf = (NumericUpDown)Forms.Utils.GetControlByName("Shelf", this._form.Controls);
			_shelf.ValueChanged += new EventHandler(_location_ValueChanged);
			_rack = (NumericUpDown)Forms.Utils.GetControlByName("Rack", this._form.Controls);
			_rack.ValueChanged += new EventHandler(_location_ValueChanged);
			_box = (NumericUpDown)Forms.Utils.GetControlByName("Box", this._form.Controls);
			_box.ValueChanged += new EventHandler(_location_ValueChanged);

			this._form.btnRemove.Visible = false;
			this._form.btnNew.Visible = false;
		}

		public override void InitializeEmptyControls()
		{
			base.InitializeEmptyControls();
			_freezer.SelectedIndex = -1;
			_reasonNotUsed.SelectedIndex = -1;
		}

		protected override void SetControlsEnabled(bool enable)
		{
			base.SetControlsEnabled(enable);
			_btnClear.Enabled = enable;

			if (enable == false)
			{
				_btnUpdateSelected.Enabled = enable; ;
				_btnUpdateAll.Enabled = enable;
				_btnRemoveBatch.Enabled = enable;
			}

			_selectLocation.Enabled = enable;
			_reasonNotUsed.Enabled = false;
			_reasonNotUsed.SelectedIndex = -1;
			_reasonNotUsed.SelectedIndex = -1;

			_freezer.Enabled = enable;
			_freezer.SelectedIndex = -1;
			_freezer.SelectedIndex = -1;
			_shelf.Enabled = enable;
			_shelf.Value = 0;
			_rack.Enabled = enable;
			_rack.Value = 0;
			_box.Enabled = enable;
			_box.Value = 0;

			_note.Enabled = enable;
			_note.Text = "";

			_notUsed.Enabled = enable;
			_notUsed.Checked = false;
			_noShow.Enabled = enable;
			_noShow.Checked = false;

			_chkIncludeComment.Enabled = enable;
			_chkIncludeComment.Checked = false;
		}
		#endregion initialize

		public override void GenericClick(Control sender)
		{
			if (sender.Name == "btnUpdateSelected")
				UpdateSelected();
			if (sender.Name == "btnUpdateAll")
				UpdateAll();
			if (sender.Name == "btnRemoveBatch")
				RemoveBatch();
			if (sender.Name == "btnClear")
				ClearInfo();
			if (sender.Name == "btnPrint")
				DoPrint();
			if (sender.Name == "SelectLocation")
				SelectLocation();

		}

		#region select location
		public override void Cancel()
		{
			base.Cancel();
		}

		private void SelectLocation()
		{
			_selectLocation.Enabled = false;
			int protocol = 0;
			string test = "";
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			GridRangeInfoList list;

			list = grid.Selections.GetSelectedRows(true, false);
			if (list.Count > 0)
			{
				GridRangeInfo range = list[0];
				int row = range.Top;

				protocol = (int)grid[row, 3].CellValue;
				test = grid[row, 5].Text;
			}


			SelectLocationDlg sld = new SelectLocationDlg(test, protocol, grid, this._form.Text);
			sld.Owner = this._form;
			sld.SelectLocationEvent += new SelectLocationDlg.SelectLocationEventHandler(sld_SelectLocationEvent);
			sld.Closing += new CancelEventHandler(sld_Closing);
			sld.Show();
		}

		private void sld_SelectLocationEvent(object sender, SelectLocationEventArgs e)
		{
			DisplayLocationInControls(e.Location);
		}

		private void sld_Closing(object sender, CancelEventArgs e)
		{
			SelectLocationDlg sld = (SelectLocationDlg)sender;
			sld.SelectLocationEvent -= new SelectLocationDlg.SelectLocationEventHandler(sld_SelectLocationEvent);
			sld.Closing -= new CancelEventHandler(sld_Closing);
			if (this._formMode == EditMode.Edit || this._formMode == EditMode.New)
				this._selectLocation.Enabled = true;
		}

		#endregion select location
		#region search
		public override void Search(object sender)
		{
			Control ctl = (Control)sender;
			ctl.Enabled = false;

			SearchSamples spd = new SearchSamples();
			spd.ShowDialog(this._form);
			if (spd.SearchChoice == 0)
				base.Search(sender);
			else if (spd.SearchChoice == 1)
				SelectByLabel();

			ctl.Enabled = true;
		}

		private void SelectByLabel()
		{

			Cursor.Current = Cursors.WaitCursor;

			SearchInfo si = (SearchInfo)this.FormInfo.SearchFormInfo["TestSamples"];
			if (si == null)
			{
				MessageBox.Show("Search criteria is not defined.", "Search Criteria Not Fount",
					MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			FormSearch fs = new FormSearch();
			//set the title bar
			//fs.Text = si.Name + " Search";

			//get the search fields			
			foreach (ReportColumn rc in si.SearchFields)
				fs.SearchFields.Items.Add(rc);

			//design list view for result fields			
			ListView lvw = fs.SearchResults;
			lvw.Columns.Clear();
			if (lvw != null)
			{
				foreach (ReportColumn rc in si.SearchResultCols)
				{
					ColumnHeader ch = new ColumnHeader();
					ch.Text = rc.DisplayName;
					ch.Width = -2;
					lvw.Columns.Add(ch);
				}
			}

			SearchSamplesController sc = new SearchSamplesController(fs, si);
			fs.Controller = sc;
			fs.Owner = this._form;
			sc.ItemSelected += new BaseForms.BusinessLogicEvents.BLSelectedItemEventHandler(sc_ItemSelected);
			fs.Closing += new CancelEventHandler(fs_Closing);
			IsSearchVisible = true;
			fs.Show();
		}

		private void sc_ItemSelected(object sender, BLReturnIDEventArgs e)
		{
			if (e.ID > 0)
			{
				Console.WriteLine("Selected ID: " + e.ID.ToString());
				if (GetData(e.ID))
				{
					if (this.FormMode == EditMode.Load)
						SetFormMode(EditMode.Read);
				}
			}
		}

		private void fs_Closing(object sender, CancelEventArgs e)
		{
			IsSearchVisible = false;
			this._form.btnSearch.Enabled = true;
		}
		#endregion search
		#region events
		private void _notUsed_CheckedChanged(object sender, EventArgs e)
		{
			if (ignoreEvent)
			{
				ignoreEvent = false;
				return;
			}

			if (_notUsed.Checked)
			{
				ignoreEvent = true;
				ClearLocation();
				if (!this._reasonNotUsed.Enabled)
					this._reasonNotUsed.Enabled = true;
			}
			else
			{
				if (this._reasonNotUsed.Enabled)
				{
					this._reasonNotUsed.Text = "";
					this._reasonNotUsed.Enabled = false;
				}
			}

			if (_noShow.Checked)
			{
				ignoreEvent = true;
				_noShow.Checked = false;
			}
		}
		private void _noShow_CheckedChanged(object sender, EventArgs e)
		{
			if (ignoreEvent)
			{
				ignoreEvent = false;
				return;
			}

			if (_noShow.Checked)
			{
				ignoreEvent = true;
				ClearLocation();
			}
			if (_notUsed.Checked)
			{
				ignoreEvent = true;
				_notUsed.Checked = false;
				if (this._reasonNotUsed.Enabled)
				{
					this._reasonNotUsed.Text = "";
					this._reasonNotUsed.Enabled = false;
				}
			}
		}

		private void _location_ValueChanged(object sender, EventArgs e)
		{
			if (ignoreEvent)
				return;

			if (_freezer.SelectedIndex != -1 ||
				_shelf.Value != 0 ||
				_rack.Value != 0 ||
				_box.Value != 0)
			{
				if (_noShow.Checked)
				{
					ignoreEvent = true;
					_noShow.Checked = false;
				}
				else if (_notUsed.Checked)
				{
					ignoreEvent = true;
					_notUsed.Checked = false;
					if (this._reasonNotUsed.Enabled)
					{
						this._reasonNotUsed.Text = "";
						this._reasonNotUsed.Enabled = false;
					}
				}
			}
		}
		#endregion events

		#region get display data
		private void ClearInfo()
		{
			ClearLocation();
			this._note.Text = "";
			this._noShow.Checked = false;
			this._reasonNotUsed.SelectedIndex = -1;
			this._reasonNotUsed.SelectedIndex = -1;
			this._reasonNotUsed.Enabled = false;
			this._notUsed.Checked = false;
			this._chkIncludeComment.Checked = false;
		}
		private void ClearLocation()
		{
			this._freezer.SelectedIndex = -1;
			this._freezer.SelectedIndex = -1;
			this._shelf.Value = 0;
			this._rack.Value = 0;
			this._box.Value = 0;

			if (ignoreEvent)
				ignoreEvent = false;
		}
		protected override void grd_CellDoubleClick(object sender, GridCellClickEventArgs e)
		{
			if (e.RowIndex < 1)
				return;
			if (this.FormMode == EditMode.Edit || this.FormMode == EditMode.New)
				FillControlsWithRowData(e.RowIndex);
		}

		private void FillControlsWithRowData(int row)
		{
			GridControl grid = ((BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"]).Grid;
			//location			
			string sVal = grid[row, 6].Text;
			DisplayLocationInControls(sVal);
			this._note.Text = grid[row, 7].Text;

			if (grid[row, 8].Text == "1")
				this._notUsed.Checked = true;
			else
				this._notUsed.Checked = false;
			if (grid[row, 9].Text == "1")
				this._noShow.Checked = true;
			else
				this._noShow.Checked = false;
		}

		private void DisplayLocationInControls(string location)
		{
			if (location.Length == 0)
			{
				ClearLocation();
				return;
			}

			string[] a = location.Split(',');
			foreach (string s in a)
			{
				if (s.StartsWith("Fz"))
				{
					this._freezer.SelectedValue = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Sf"))
				{
					this._shelf.Value = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Rk"))
				{
					this._rack.Value = Convert.ToInt32(s.Substring(3));
				}
				if (s.StartsWith("Bx"))
				{
					this._box.Value = Convert.ToInt32(s.Substring(3));
				}
			}
		}

		#endregion get display data

		#region update remove batch
		private void RemoveBatch()
		{
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);
			if (list.Count == 0)
				return;

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			ArrayList alRows = new ArrayList();
			int row = 0;
			int top = 0;
			int bottom = 0;
			for (int i = 0; i < list.Count; i++)
			{
				top = list[i].Top;
				bottom = list[i].Bottom;
				if (bottom > top)
					GetSelectedRows(alRows, top, bottom);
				else
					alRows.Add(list[i].Top);
			}
			for (int i = 0; i < alRows.Count; i++)
			{
				row = (int)alRows[i];
				row -= i;
				DataRow dr = (DataRow)fgbl.Grid[row, 0].Tag;
				dr.RejectChanges();
				fgbl.RemoveRow(row);
			}
		}

		private void GetSelectedRows(ArrayList alRows, int top, int bottom)
		{
			int rows = bottom - top + 1;
			for (int i = 0; i < rows; i++)
				alRows.Add(top + i);
		}

		private void UpdateSelected()
		{
			if (!VerifyAddToBatch(0))
				return;

			Sample samp = this.SetReplacementColumns();
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			GridRangeInfoList list;
			list = grid.Selections.GetSelectedRows(true, false);

			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			foreach (GridRangeInfo range in list)
			{
				for (int i = range.Top; i <= range.Bottom; i++)
					fgbl.ReplaceRow(samp, i);
			}
		}

		private void UpdateAll()
		{
			if (!VerifyAddToBatch(0))
				return;

			Sample samp = this.SetReplacementColumns();
			BLCoreLabFormGridBaseImpl fgbl = (BLCoreLabFormGridBaseImpl)this._gridBLs["TestSamples"];

			for (int i = 1; i <= fgbl.Grid.RowCount; i++)
				fgbl.ReplaceRow(samp, i);
		}

		private Sample SetReplacementColumns()
		{
			Sample samp = new Sample();
			samp.ReasonNotUsed = 0;
			if (_notUsed.Checked || _noShow.Checked)
			{
				samp.NoShow = _noShow.Checked;
				samp.NotUsed = _notUsed.Checked;
				if (this._reasonNotUsed.SelectedIndex > -1)
					samp.ReasonNotUsed = (int)_reasonNotUsed.SelectedValue;
			}
			else
				samp.Location = GetFormatatedLocation();
			if (this._chkIncludeComment.Checked)
				samp.Note = this._note.Text;
			return samp;
		}

		private string GetFormatatedLocation()
		{
			string location = "Fz:" + this._freezer.SelectedValue.ToString() + "," +
				"Sf:" + this._shelf.Value.ToString() + "," +
				"Rk:" + this._rack.Value.ToString() + "," +
				"Bx:" + this._box.Value.ToString();
			return location;
		}

		private bool VerifyAddToBatch(int type)
		{
			if (_notUsed.Checked || _noShow.Checked)
				return true;
			if (!VerifyLocation())
			{
				MessageBox.Show(this._form, "The location is invalid.", "Invalid Location", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return false;
			}
			return true;
		}

		private bool VerifyLocation()
		{
			if (this._freezer.SelectedIndex == -1)
				return false;
			if (this._shelf.Value == 0)
				return false;
			if (this._shelf.Value > 9)
				return false;
			if (this._rack.Value > 9)
				return false;
			if (this._box.Value == 0)
				return false;
			return true;
		}
		#endregion add batch

		#region Save
		public override bool Save()
		{
			Cursor.Current = Cursors.WaitCursor;
			StringBuilder sb = new StringBuilder();
			string message = "";

			if (!VerifyGrids())
				return false;

			Microsoft.Practices.EnterpriseLibrary.Data.Database db = DatabaseFactory.CreateDatabase();
			using (DbConnection conn = db.CreateConnection())
			{
				try
				{
					conn.Open();
					DbTransaction trans = conn.BeginTransaction();

					//just need to handle the grid
					if (this._gridBLs != null)
					{
						if (!SaveGrids(out message, db, trans))
						{
							trans.Rollback();
							sb.Append("Grid data " + this._formInfo.Name + " could not be saved.");
							sb.Append(Environment.NewLine);
							sb.Append("Error: " + message);
							MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return false;
						}
					}

					trans.Commit();
					ResetGrids();
					//confirmation dialog
					MessageBox.Show("Record was saved.", "Save Confirmation",
						MessageBoxButtons.OK, MessageBoxIcon.Information);

					bool shouldClose = (bool)this._configData["CloseOnSave"];

					if (shouldClose)
					{
						this._isClosing = true;
						this._form.Close();
					}
					else
					{
						this._fcManager.CurrentRow.AcceptChanges();
						SetGridsAcceptChanges();
						SetFormMode(EditMode.Read);
					}
				}
				catch (Exception ex)
				{
					//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
					sb.Append("Form could not be saved.");
					sb.Append(Environment.NewLine);
					sb.Append("Error message: " + ex.Message);
					MessageBox.Show(this._form, sb.ToString(), "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return false;
				}
				finally
				{
					//if (conn != null)
					//    conn.Close();
				}
				return true;
			}
		}
		#endregion save

		#region print
		private void DoPrint()
		{
			if (!HasRows())
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("There are no labels to print.");
				sb.Append(Environment.NewLine);
				MessageBox.Show(this._form, sb.ToString(), "No Labels", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			if (HasRowNoID())
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("You must press save to give the new labels an ID.");
				sb.Append(Environment.NewLine);
				MessageBox.Show(this._form, sb.ToString(), "No Label ID", MessageBoxButtons.OK, MessageBoxIcon.Stop);
				return;
			}

			if (_chkPrintReport.Checked)
				PrintReport(0);

			if (_chkPerPatient.Checked)
				PrintReport(1);
		}

		private void PrintReport(int type)
		{
			StringBuilder sb = new StringBuilder();
			string formatFile = System.Windows.Forms.Application.StartupPath + "\\Bartender\\" + CremaConstants.LabelReportFormatFile;

			this._pDoc = new PrintDocument();
			this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (this._pDlg.ShowDialog(this._form) == DialogResult.Cancel)
				return;

			bool doClear = false;
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			Cursor.Current = Cursors.WaitCursor;

			if (type == 0)
				this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage);
			else
				this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPerPatient);

			_sBatch = this._currentPrimaryID.ToString();

			try
			{
				System.Windows.Forms.Application.DoEvents();
				//				_btApp = new BarTender.ApplicationClass();							
				//				BarTender.Format btFmt = _btApp.Formats.Open(formatFile, true, "");

				_page = 1;
				_startRow = 1;
				_startRange = 0;

				if (this._chkPrintSelected.Checked)
				{
					if (grid.Selections.Count == 0)
					{
						sb.Append("Select rows to print or uncheck the 'Print Select Rows' check box.");
						MessageBox.Show(this._form, sb.ToString(), "No Rows Selected", MessageBoxButtons.OK, MessageBoxIcon.Stop);
						return;
					}
					else
					{
						//get the start row								
						GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
						GridRangeInfo range = (GridRangeInfo)list[0];
						_startRow = range.Top;
					}
				}
				else
				{
					grid.Selections.Add(GridRangeInfo.Rows(1, grid.RowCount));
					doClear = true;
				}

				this._pDoc.Print();
				if (doClear)
					grid.Selections.Clear();
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not start bartender server");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this._form, sb.ToString(), "Bartender Server Failed To Start", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//				if(_btApp != null)
				//				{
				//					_btApp.Quit(BarTender.BtSaveOptions.btDoNotSaveChanges);
				//					_btApp = null;
				//				}

				if (type == 0)
					this._pDoc.PrintPage -= new PrintPageEventHandler(_pDoc_PrintPage);
				else
					this._pDoc.PrintPage -= new PrintPageEventHandler(_pDoc_PrintPerPatient);
			}
		}

		private void _pDoc_PrintPage(object sender, PrintPageEventArgs e)
		{

			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			string batchDate = ((Syncfusion.Windows.Forms.Tools.DateTimePickerAdv)Forms.Utils.GetControlByName("BatchInDate", this._form.Controls)).Value.ToShortDateString();
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);
			//print title and subtitle
			if (this._page == 1)
			{
				PrintingUtils.PrintCenter("Core Lab - Test Samples Check-in Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;

				sb.Append("Batch #: " + _sBatch);
				sb.Append("   Batch Date: " + batchDate);
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("Core Lab - Test Samples Check-in Report - Batch #: " + _sBatch + " continued");
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;

			//print heading
			float c1 = 25; //+125
			float c2 = 150; //+75
			float c3 = 225; //+125			
			float c4 = 350; //150
			float c5 = 500; //150			
			float c6 = 750; //200

			float c1W = 125; //id
			float c2W = 75;  //protocol
			float c3W = 125; //patient 			
			float c4W = 150; //test			
			float c5W = 150; //location
			float c6W = 150;  //note

			RectangleF rec = new RectangleF();

			gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 23, yPos, pageWidth - 48, lineHeight);

			PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
			gfx.DrawString("Test ID", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
			gfx.DrawString("Protocol", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
			gfx.DrawString("Patient", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
			gfx.DrawString("Test Type", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
			gfx.DrawString("Location", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
			gfx.DrawString("Note", ColumnHeadFont, Brushes.Black, rec);
			yPos += lineHeight;

			lineHeight = prntFont.GetHeight(e.Graphics) + 18;
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			float yDraw;
			int iVal = 0;
			string sVal = "";
			PatientInfo pi = null;
			DateTime dtVal = new DateTime(0);

			GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
			for (int i = _startRange; i < list.Count; i++)
			{
				GridRangeInfo range = (GridRangeInfo)list[i];
				for (int row = range.Top; row <= range.Bottom; row++)
				{
					if (row < _startRow)
						row = _startRow;

					if (curLine == maxLines)
					{
						_startRow = row;
						_startRange = i;
						this._page++;
						e.HasMorePages = true;
						return;
					}


					yDraw = yPos + 5;
					//test id
					iVal = (int)grid[row, 1].CellValue;
					//					_labelImage = CoreLabUtils.SetLabelFormatID(iVal.ToString("0000"), this._btApp);							
					//					gfx.DrawImage(this._labelImage,c1+5, yDraw, c1W, lineHeight);
					PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
					gfx.DrawString(iVal.ToString("0000"), prntFont, Brushes.Black, rec, fmt);

					//protocol
					PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
					sVal = grid[row, 3].Text;
					gfx.DrawString(sVal.ToString(), prntFont, Brushes.Black, rec);

					//patient					
					PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
					pi = (PatientInfo)grid[row, 4].Tag;
					if (pi.Name.Length > 0)
						sVal = pi.Name + "/" + pi.GetMrnOrOtherIdentifier();
					else
						sVal = pi.GetMrnOrOtherIdentifier();
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//test
					PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
					sVal = grid[row, 5].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//location
					PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
					if (grid[row, 8].Text == "1")
						sVal = "Not Used";
					else if (grid[row, 9].Text == "1")
						sVal = "No Show";
					else
						sVal = grid[row, 6].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
					sVal = grid[row, 7].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
					yPos += lineHeight;
					curLine++;
				}
			}
		}

		private void _pDoc_PrintPerPatient(object sender, PrintPageEventArgs e)
		{

			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			string batchDate = ((Syncfusion.Windows.Forms.Tools.DateTimePickerAdv)Forms.Utils.GetControlByName("BatchInDate", this._form.Controls)).Value.ToShortDateString();
			GridControl grid = (GridControl)Forms.Utils.GetControlByName("TestSamples", this._form.Controls);

			//print title and subtitle
			if (this._page == 1)
			{
				PrintingUtils.PrintCenter("Core Lab - Test Samples Check-in Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;

				sb.Append("Batch #: " + _sBatch);
				sb.Append("   Batch Date: " + batchDate);
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("Core Lab - Test Samples Check-in Report - Batch #: " + _sBatch + " continued");
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;

			//print heading
			float c1 = 25; //+125
			float c2 = 150; //+75
			float c3 = 225; //+125			
			float c4 = 350; //150
			float c5 = 500; //150			
			float c6 = 750; //200

			float c1W = 125; //id
			float c2W = 75;  //protocol
			float c3W = 125; //patient 			
			float c4W = 150; //test			
			float c5W = 150; //location
			float c6W = 150;  //note

			RectangleF rec = new RectangleF();

			gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 23, yPos, pageWidth - 48, lineHeight);

			PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
			gfx.DrawString("Test ID", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
			gfx.DrawString("Protocol", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
			gfx.DrawString("Patient", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
			gfx.DrawString("Test Type", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
			gfx.DrawString("Location", ColumnHeadFont, Brushes.Black, rec);
			PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
			gfx.DrawString("Note", ColumnHeadFont, Brushes.Black, rec);
			yPos += lineHeight;

			lineHeight = prntFont.GetHeight(e.Graphics) + 18;
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			float yDraw;
			int iVal = 0;
			string sVal = "";
			PatientInfo pi = null;
			DateTime dtVal = new DateTime(0);

			GridRangeInfoList list = grid.Selections.GetSelectedRows(true, false);
			//assign current patient
			this._curPatient = (int)grid[_startRow, 4].CellValue;
			for (int i = _startRange; i < list.Count; i++)
			{
				GridRangeInfo range = (GridRangeInfo)list[i];
				for (int row = range.Top; row <= range.Bottom; row++)
				{
					if (row < _startRow)
						row = _startRow;

					pi = (PatientInfo)grid[row, 4].Tag;
					if (curLine == maxLines || this._curPatient != pi.ID)
					{
						_startRow = row;
						_startRange = i;
						_curPatient = pi.ID;
						this._page++;
						e.HasMorePages = true;
						return;
					}


					yDraw = yPos + 5;
					//test id
					iVal = (int)grid[row, 1].CellValue;
					//					_labelImage = CoreLabUtils.SetLabelFormatID(iVal.ToString("0000"), this._btApp);							
					//					gfx.DrawImage(this._labelImage,c1+5, yDraw, c1W, lineHeight);
					PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
					gfx.DrawString(iVal.ToString("0000"), prntFont, Brushes.Black, rec, fmt);

					//protocol
					PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
					sVal = grid[row, 3].Text;
					gfx.DrawString(sVal.ToString(), prntFont, Brushes.Black, rec);

					//patient					
					PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
					if (pi.Name.Length > 0)
						sVal = pi.Name + "/" + pi.GetMrnOrOtherIdentifier();
					else
						sVal = pi.GetMrnOrOtherIdentifier();
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//test
					PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
					sVal = grid[row, 5].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					//location
					PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
					if (grid[row, 8].Text == "1")
						sVal = "Not Used";
					else if (grid[row, 9].Text == "1")
						sVal = "No Show";
					else
						sVal = grid[row, 6].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
					sVal = grid[row, 7].Text;
					gfx.DrawString(sVal, prntFont, Brushes.Black, rec, fmt);

					gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
					yPos += lineHeight;
					curLine++;
				}
			}
		}
		#endregion print


	}
}
